<template>
  <div class="white-bg commonBoxmp">
    <TableV2
      :apiFunction="listDept"
      class="flex1"
      dataKey="data"
      ref="tableV2Ref"
      :columns="state.columnData"
    >
      <template #tableHeader>
        <div class="jcb aic w100">
          <h3 class="mx15">部门管理</h3>
          <el-button type="primary" @click="handleAdd">添加部门</el-button>
        </div>
      </template>

      <template #operation>
        <el-table-column label="操作" fixed="right" width="160px" align="left">
          <template #default="scope">
            <el-button type="text" @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>
    </TableV2>

    <el-dialog
      v-model="state.userVisible"
      :title="state.title"
      width="50%"
      destroy-on-close
      center
    >
      <el-form
        ref="ruleFormRef"
        :model="state.form"
        :rules="state.rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="24" v-if="state.form.parentId !== 0">
            <el-form-item label="上级部门">
              <el-cascader
                :options="state.deptOptions"
                v-model="state.form.parentId"
                class="w100"
                :props="{
                  checkStrictly: true,
                  value: 'deptId',
                  label: 'deptName',
                }"
                clearable
                @change="handleCascader"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                v-model="state.form.deptName"
                placeholder="请输入部门名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="state.form.orderNum" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input
                v-model="state.form.leader"
                placeholder="请输入负责人"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="state.form.phone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <selectDict
                class="w100"
                deptId="sys_normal_disable"
                v-model="state.form.status"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="state.form.email"
                maxlength="50"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.userVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "/@ts/components/table/Column";
import selectDict from "/@/components/selectDict/index.vue";
import DictTag from "/@/components/DictTag/index.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "/@ts/axios/urlApi/system/dept";

import formatTool from "/@ts/hooks/format";
const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange, handleTree, getDict } = formatTool();
let dict: any = reactive({
  sys_job_status: [],
});
onMounted(async () => {
  dict.sys_job_status = await getDict("sys_job_status");
});
const tableV2Ref = ref();
const dialogVisible = ref(true);
const state: any = reactive({
  typeOptions: [],
  // 表格基础配置 start
  form: {},
  title: "",
  rules: {
    dictLabel: [
      { required: true, message: "数据标签不能为空", trigger: "blur" },
    ],
    dictValue: [
      { required: true, message: "数据键值不能为空", trigger: "blur" },
    ],
    dictSort: [
      { required: true, message: "数据顺序不能为空", trigger: "blur" },
    ],
  },
  dateRange: [], //时间范围筛选

  height: 0,
  tableData: [],
  deptOptions: [],
  columnData: [
    {
      label: "部门名称",
      prop: "deptName",
      visible: true,
    },
    {
      label: "排序",
      prop: "orderNum",
      visible: true,
    },

    {
      label: "备注",
      prop: "remark",
      visible: true,
    },

    {
      label: "状态",
      prop: "status",
      visible: true,
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_job_status}
          ></DictTag>
        );
      },
    },
    {
      label: "创建时间",
      prop: "createTime",
    },
  ],
  loading: false,
  defaultDictType: "",
  // 表格基础配置 end
});
// 表格基础配置 start
const pageInfo = reactive<PageInfoConfig>({
  currentPage: 1,
  total: 10,
  pageSize: 10,
  pageSizes: [10, 20, 30, 40],
  layout: "total, prev, pager, next,sizes",
});
const queryParams = reactive({
  dictType: undefined,
  pageNum: 1,
  pageSize: 10,
});

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};
// 表格基础配置 end
const handleCascader = (val: any) => {
  if (val) {
    state.form.parentId = val[val.length - 1];
  }
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  if (state.form.parentId && Array.isArray(state.form.parentId)) {
    state.form.parentId = state.form.parentId[state.form.parentId.length - 1];
  }
  if (state.form.deptId != undefined) {
    updateDept(state.form).then((response: ResponseConfig) => {
      ElMessage.success("修改成功");
      state.userVisible = false;
      getList();
    });
  } else {
    addDept(state.form).then((response: ResponseConfig) => {
      ElMessage.success("新增成功");
      state.userVisible = false;
      getList();
    });
  }
};
const handleDelete = (row: any) => {
  const deptId = row.deptId;
  ElMessageBox.confirm('是否确认删除编号为"' + row.deptName + '"的数据项？')
    .then(function () {
      return delDept(deptId);
    })
    .then(() => {
      ElMessage.success("删除成功");
      getList();
    })
    .catch(function () {});
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  const deptId = row.deptId;
  getDept(deptId).then((response: ResponseConfig) => {
    state.title = "修改部门";
    state.form = response.data;

    state.userVisible = true;
    listDeptExcludeChild(row.deptId).then((response: ResponseConfig) => {
      state.deptOptions = handleTree(response.data, "deptId");
      if (state.deptOptions.length == 0) {
        const noResultsOptions = {
          deptId: state.form.parentId,
          deptName: state.form.parentName,
          children: [],
        };
        state.deptOptions.push(noResultsOptions);
      }
    });
  });
};
const handleAdd = () => {
  listDept().then((response: ResponseConfig) => {
    state.deptOptions = handleTree(response.data, "deptId");
  });
  state.form = {
    dictType: queryParams.dictType,
  };
  state.title = "添加字典数据";
  state.userVisible = true;
};
// 表格基础配置 end

const getTypeList = () => {
  //   optionselect().then((response:any) => {
  //   state.typeOptions = response.data;
  // });
};
//查询用户列表
const getList = () => {
  state.loading = true;
  listDept(addDateRange(queryParams, state.dateRange)).then(
    (response: ResponseConfig) => {
      state.tableData = handleTree(response.data, "deptId");
      state.loading = false;
    },
  );
};
const ruleFormRef = ref<FormInstance>();
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss"></style>
